﻿namespace EyeOpen.Editing.Windows
{
	using System.Linq;

	public class CustomerValidator 
		: Validator<Customer>
	{
		public override string Validate(Customer obj, string propertyName)
		{
			if (propertyName == Property(x => x.Name))
			{
				return string.IsNullOrWhiteSpace(obj.Name) ? "Must be not empty." : null;
			}

			if (propertyName == Property(x => x.Age))
			{
				if (obj.Age < 18)
				{
					return "Age must be greather than 18.";
				}
			}

			return ValidateOnStorage(obj);
		}

		private string ValidateOnStorage(Customer obj)
		{
			var customerRepository = 
				DependencyResolver
					.Resolve<CustomerRepository>();

			if (customerRepository.GetAll().Any(c => c.Name == obj.Name))
			{
				return string.Format("Customer with name {0} already exists.", obj.Name);
			}

			return null;
		}
	}
}